<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>6图连连看</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: "Arial", "微软雅黑";
        }
        body {
            background-color: #f5f5f5;
            padding: 20px;
        }
        .game-container {
            max-width: 500px;
            margin: 0 auto;
            text-align: center;
        }
        .game-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .timer {
            font-size: 18px;
            color: #333;
            font-weight: bold;
        }
        button {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            background-color: #4CAF50;
            color: white;
            font-size: 16px;
            cursor: pointer;
            transition: background 0.3s;
        }
        button:hover {
            background-color: #45a049;
        }
        .game-table {
            border-collapse: separate;
            border-spacing: 10px;
            margin: 0 auto;
        }
        .game-cell {
            width: 100px;
            height: 100px;
            border: 2px solid #4CAF50;
            border-radius: 8px;
            background-color: white;
            cursor: pointer;
            transition: all 0.3s;
            overflow: hidden;
        }
        .game-cell img {
            width: 100%;
            height: 100%;
            object-fit: cover; /* 保持图片比例，填充单元格 */
        }
        /* 选中状态 */
        .game-cell.active {
            border-color: #ff4444;
            transform: scale(1.05);
        }
        /* 消除状态 */
        .game-cell.removed {
            border-color: #ddd;
            background-color: #eee;
            cursor: default;
            opacity: 0.5;
        }
        .victory-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.7);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 999;
        }
        .modal-content {
            background: white;
            padding: 30px;
            border-radius: 8px;
            text-align: center;
        }
        .modal-content h2 {
            color: #333;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
<div class="game-container">
    <div class="game-header">
        <div class="timer">已用时：<span id="time">0</span>秒</div>
        <button id="restart-btn">重新开始</button>
    </div>
    <table class="game-table" id="game-table"></table>
</div>

<!-- 胜利弹窗 -->
<div class="victory-modal" id="victory-modal">
    <div class="modal-content">
        <h2>恭喜通关！</h2>
        <p>总用时：<span id="final-time">0</span>秒</p>
        <button id="play-again-btn">再玩一次</button>
    </div>
</div>

<script>
    // 1. 游戏配置
    const config = {
        picCount: 6,    // 6张随机图片
        cellCount: 12,  // 总格子数（6×2）
        rows: 3,        // 3行
        cols: 4,        // 4列
        picIds: [237, 106, 152, 201, 119, 188], // picsum固定图片ID（确保6张不同图）
        selectedCells: [], // 存储选中的格子
        isPlaying: false,  // 是否正在游戏
        timer: null,       // 计时器
        time: 0            // 计时时间（秒）
    };

    // 2. 初始化游戏
    function initGame() {
        // 重置游戏状态
        config.selectedCells = [];
        config.time = 0;
        document.getElementById('time').textContent = 0;
        document.getElementById('victory-modal').style.display = 'none';

        // 生成图片数组（6张图各存2次，然后打乱）
        const picArr = [];
        config.picIds.forEach(id => {
            picArr.push(`https://picsum.photos/id/${id}/100/100`); // 100x100适配格子
            picArr.push(`https://picsum.photos/id/${id}/100/100`);
        });
        shuffleArr(picArr); // 打乱数组

        // 渲染游戏表格
        const table = document.getElementById('game-table');
        table.innerHTML = '';
        let cellIndex = 0;
        for (let i = 0; i < config.rows; i++) {
            const tr = document.createElement('tr');
            for (let j = 0; j < config.cols; j++) {
                const td = document.createElement('td');
                td.className = 'game-cell';
                td.dataset.pic = picArr[cellIndex]; // 存储图片地址（用于匹配）

                // 添加图片
                const img = document.createElement('img');
                img.src = picArr[cellIndex];
                td.appendChild(img);

                // 绑定点击事件
                td.addEventListener('click', handleCellClick);
                tr.appendChild(td);
                cellIndex++;
            }
            table.appendChild(tr);
        }

        // 开始计时
        config.isPlaying = true;
        startTimer();
    }

    // 3. 打乱数组（Fisher-Yates 洗牌算法）
    function shuffleArr(arr) {
        for (let i = arr.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [arr[i], arr[j]] = [arr[j], arr[i]];
        }
        return arr;
    }

    // 4. 格子点击事件
    function handleCellClick(e) {
        const cell = e.target.closest('.game-cell'); // 确保点击的是格子（兼容点击图片）

        // 跳过：非游戏中、已消除、已选中的格子
        if (!config.isPlaying || cell.classList.contains('removed') || cell.classList.contains('active')) {
            return;
        }

        // 处理选中状态
        if (config.selectedCells.length < 2) {
            cell.classList.add('active');
            config.selectedCells.push(cell);

            // 选中2个格子后，判断是否匹配
            if (config.selectedCells.length === 2) {
                const [cell1, cell2] = config.selectedCells;
                if (cell1.dataset.pic === cell2.dataset.pic) {
                    // 匹配成功：标记为消除
                    setTimeout(() => {
                        cell1.classList.add('removed');
                        cell2.classList.add('removed');
                        cell1.classList.remove('active');
                        cell2.classList.remove('active');
                        config.selectedCells = [];

                        // 检查是否通关
                        checkVictory();
                    }, 500); // 延迟0.5秒，让用户看到选中效果
                } else {
                    // 匹配失败：取消选中
                    setTimeout(() => {
                        cell1.classList.remove('active');
                        cell2.classList.remove('active');
                        config.selectedCells = [];
                    }, 800); // 延迟0.8秒，让用户看清不匹配的格子
                }
            }
        }
    }

    // 5. 开始计时
    function startTimer() {
        clearInterval(config.timer); // 清除旧计时器
        config.timer = setInterval(() => {
            config.time++;
            document.getElementById('time').textContent = config.time;
        }, 1000);
    }

    // 6. 检查是否通关（所有格子都被消除）
    function checkVictory() {
        const removedCells = document.querySelectorAll('.game-cell.removed');
        if (removedCells.length === config.cellCount) {
            config.isPlaying = false;
            clearInterval(config.timer); // 停止计时

            // 显示胜利弹窗
            document.getElementById('final-time').textContent = config.time;
            document.getElementById('victory-modal').style.display = 'flex';
        }
    }

    // 7. 绑定按钮事件（重新开始、再玩一次）
    document.getElementById('restart-btn').addEventListener('click', initGame);
    document.getElementById('play-again-btn').addEventListener('click', initGame);

    // 8. 页面加载完成后初始化游戏
    window.addEventListener('load', initGame);
</script>
</body>
</html>